package com.example.huhaichao.javaVideo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.huhaichao.hhcin227.R;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    private final int HDRLEN = 50;
    private final int SZOFS = 29;
    private boolean m_stop = false;
    private boolean bright_up = false;
    private boolean bright_down = false;
    private boolean contrast_up = false;
    private boolean contrast_down = false;
    public static final boolean DEBUGGING = false;
    private String ip = null;
    private int port;
    public Button btnDisconnect;
    private ImageView show;
    private boolean videoplay = true;
    private Socket connection=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = getIntent();
        ip = intent.getStringExtra("ip");
        port = intent.getIntExtra("port", 1);
        Log.d("hhc","ip="+ip+"port="+port);
        show = (ImageView) findViewById(R.id.iv_video);
        btnDisconnect=(Button)findViewById(R.id.btnDisconnect);
        btnDisconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                videoplay=false;
                try {
                    if(connection!=null)
                        connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                finish();
            }
        });
        new Thread(){
            @Override
            public void run() {
                InputStream in;
                OutputStream out;
                byte[] buffer = new byte[50 * 1024];
                try {
                    connection = new Socket(ip, port);
                    Log.d("hhc","ip="+ip+"port="+port);
                    out= connection.getOutputStream();
                    in = connection.getInputStream();
                    while(videoplay) {
                        int n = 0;
                        int siz = 0;
                        byte[] b = {'O', 'K', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
                        if (bright_up) {
                            b[7] = 1;
                            bright_up = false;
                        }
                        if (bright_down) {
                            b[7] = 2;
                            bright_down = false;
                        }
                        if (contrast_up) {
                            b[8] = 1;
                            contrast_up = false;
                        }
                        if (contrast_down) {
                            b[8] = 2;
                            contrast_down = false;
                        }

                        out.write(b);
                        if (DEBUGGING)
                            System.out.print("-sending my header (" + Integer.toString(b.length) + ") bytes");
                        n = in.read(buffer, 0, HDRLEN);
                        if (DEBUGGING)
                            System.out.print("-read header (" + Integer.toString(n) + ") bytes");

                        if (n < HDRLEN) {
                            if (n <= 0)
                                m_stop = true;
                        } else {
                            int ssz = SZOFS;
                            siz += unsignedByteToInt(buffer[ssz + 3]) << 24;
                            siz += unsignedByteToInt(buffer[ssz + 2]) << 16;
                            siz += unsignedByteToInt(buffer[ssz + 1]) << 8;
                            siz += unsignedByteToInt(buffer[ssz]);
                            if (DEBUGGING)
                                System.out.println("** reading jpeg, size=" + Integer.toString(siz));
                            n = HDRLEN;
                            if (buffer[0] != 'S' || buffer[1] != 'P' || buffer[2] != 'C' || buffer[3] != 'A') {
                                System.out.println("*Header missing 'SPCA'");
                            } else if (siz <= 0 || siz > (512 * 1024)) {
                                siz = 0;
                                try {
                                    in.read(buffer, n, buffer.length);
                                } catch (Exception e) {
                                    if (DEBUGGING)
                                        e.printStackTrace();
                                }
                                if (DEBUGGING)
                                    System.out.println("*Illegal image size");
                            } else {
                                do {
                                    int r = 0;
                                    try {
                                        r = in.read(buffer, n, buffer.length - n);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    n += r;
                                    if (DEBUGGING)
                                        System.out.println(" chunk read, size=" + Integer.toString(r) + " total=" + Integer.toString(n));
                                }
                                while (n < (siz + HDRLEN));
                            }
                            if (DEBUGGING)
                                System.out.println("jpeg read, size=" + Integer.toString(n));
                        }
                        byte[] buffer2 = new byte[n];
                        for (int i = 0; i < n; i++)
                            buffer2[i] = buffer[i + HDRLEN];
                        Bitmap bitmap = getBitmapmapFromByte(buffer2);
                        show(bitmap);
                    }
                    try {
                        connection.close();
                    } catch (IOException e) {
                    }
                } catch (Exception e) {
                    if (DEBUGGING)
                        e.printStackTrace();
                }
                if (DEBUGGING) {
                    if (m_stop)
                        System.out.println("** worker ending (m_stop==true)");
                    else
                        System.out.println("** worker ending (m_stop==false)");
                }
                m_stop = true;
            }
        }.start();
    }
    public static int unsignedByteToInt(byte b) {
        return (int) b & 0xff;
    }

    void show(final Bitmap bitmap){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                show.setImageBitmap(bitmap);
            }
        });
    }

    public Bitmap getBitmapmapFromByte(byte[] temp){
        if(temp!=null){
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        }
        return null;
    }


}
